package cc.idoone.spring_boot_hello.upload;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;

@Controller
@RequestMapping("/upload")
public class UploadController {

	/**
	 * 上传页面
	 */
	@RequestMapping(value = {"/", "/index"}, method = RequestMethod.GET)
	public String goUploadImg() {
		return "upload/uploadfile";
	}

	/**
	 * 处理文件上传
	 */
	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	@ResponseBody
	public String uploadFile(@RequestParam("myfile") MultipartFile file, HttpServletRequest request) throws Exception {
		if (file.isEmpty()) {
			return "文件为空";
		}

		String fileName = file.getOriginalFilename();
		String contentType = file.getContentType();
		System.out.println("fileName --> " + fileName);
		System.out.println("getContentType --> " + contentType);
		String filePath = request.getServletContext().getRealPath("upload/");

		uploadFile(file.getBytes(), filePath, fileName);

		return "upload success";
	}

	/**
	 * 处理多文件上传
	 */
	@RequestMapping(value = "/uploadFiles", method = RequestMethod.POST)
	@ResponseBody
	public String uploadFiles(@RequestParam("myfile") MultipartFile[] files, HttpServletRequest request) throws Exception {
		if (files.length == 0) {
			return "文件为空";
		}

		for (MultipartFile file : files) {
			uploadFile(file, request);
		}

		return "upload success";
	}

	/**
	 * 保存文件
	 */
	private static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
		File targetFile = new File(filePath);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		System.out.println(targetFile.getAbsolutePath());

		FileOutputStream out = new FileOutputStream(new File(targetFile, fileName));
		out.write(file);
		out.flush();
		out.close();
	}
}
